#include "StdAfx.h"
#include "LineageBuffer.h"
#include "BufferConstraint.h"
#include "StreamPage.h"
LineageBuffer::LineageBuffer( int lineageNumber):lineageNumber(lineageNumber)
{


	this->freePositionHead.pageIndex=0;
	this->freePositionHead.chunkIndex=0;
}


LineageBuffer::~LineageBuffer(void)
{
}


void LineageBuffer::insertLineage(Lineage& lineage,Element& outputElement)
{
	assert(!isFull());


	this->setElementByMemoryPosition(outputElement,this->freePositionHead);
	if(this->lineagePositionMap.find(lineage)!=this->lineagePositionMap.end())//this lineage is already exists
	{
		return;
	}
	this->lineagePositionMap.insert(make_pair(lineage,this->freePositionHead));
	this->getNextPosition(this->freePositionHead,this->freePositionHead);

	
}
bool LineageBuffer::getAndDeleteElement(Lineage& lineage, Element& outputElement)
{
	
	std::map<Lineage, MemoryPosition>::iterator it;
	it = this->lineagePositionMap.find(lineage);
	if(it==this->lineagePositionMap.end())
	{
		return false;
	}
	
	MemoryPosition elementPosition = it->second;
	this->getElementByMemoryPosition(outputElement,elementPosition);
	this->setNextPosition(elementPosition,this->freePositionHead);
	this->freePositionHead = elementPosition;
	this->lineagePositionMap.erase(it);
	return true;
}
bool LineageBuffer::isFull(void)
{
	bool ret;
	if(!isValidMemoryPosition(freePositionHead))
	{
		ret = this->allocateNewPage();
		if(ret == false)
		{
			return true;
		}
		this->freePositionHead.pageIndex = this->getPageNumber()-1;
		this->freePositionHead.chunkIndex = 0;

	}

	return false;
}
